<template>
  <div class="book-edit">
    <div class="edit-container">
      <div class="book-info">
        <h2>图书信息</h2>
        <el-form :model="bookForm" label-width="100px">
          <el-form-item label="书名">
            <el-input v-model="bookForm.bookName" disabled />
          </el-form-item>
          <el-form-item label="作者">
            <el-input v-model="bookForm.author" disabled />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="bookForm.price" disabled />
          </el-form-item>
          <el-form-item label="库存">
            <el-input v-model="bookForm.stock" disabled />
          </el-form-item>
        </el-form>
      </div>

      <div class="cover-upload">
        <h3>图书封面</h3>
        <div class="image-container">
          <el-image
            v-if="bookForm.coverImage"
            :src="bookForm.coverImage"
            fit="cover"
            class="cover-image"
          />
          <div v-else class="empty-cover">
            <el-icon :size="40"><Picture /></el-icon>
            <span>暂无封面</span>
          </div>
        </div>
        <el-upload
          class="upload-button"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        >
          <el-button type="primary" :loading="uploading">
            {{ uploading ? '上传中...' : '上传封面' }}
          </el-button>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const uploading = ref(false)

interface BookForm {
  bookId: number
  bookName: string
  author: string
  price: string
  stock: string
  coverImage: string
}

const bookForm = ref<BookForm>({
  bookId: 0,
  bookName: '',
  author: '',
  price: '',
  stock: '',
  coverImage: ''
})

// 上传相关配置
const uploadUrl = 'http://localhost:8080/admin/common/upload'
const headers = {
  token: localStorage.getItem('token') || ''
}

// 获取图书详情
const fetchBookDetail = async () => {
  try {
    const res = await request.get(`/user/book/detail/${route.params.id}`)
    if (res.code === 1) {
      bookForm.value = res.data
    }
  } catch (error) {
    console.error('获取图书详情失败:', error)
    ElMessage.error('获取图书详情失败')
  }
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  uploading.value = true
  return true
}

// 上传成功处理
const handleUploadSuccess = async (response: any) => {
  uploading.value = false
  if (response.code === 1) {
    // 更新图书封面
    try {
      const updateRes = await request.put(`/user/book/update/${bookForm.value.bookId}`, {
        coverImage: response.data
      })
      if (updateRes.code === 1) {
        ElMessage.success('封面上传成功')
        bookForm.value.coverImage = response.data
      }
    } catch (error) {
      console.error('更新图书封面失败:', error)
      ElMessage.error('更新图书封面失败')
    }
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败处理
const handleUploadError = () => {
  uploading.value = false
  ElMessage.error('上传失败，请重试')
}

onMounted(() => {
  if (route.params.id) {
    fetchBookDetail()
  }
})
</script>

<style scoped>
.book-edit {
  padding: 20px;
}

.edit-container {
  display: flex;
  gap: 40px;
  max-width: 1000px;
  margin: 0 auto;
}

.book-info {
  flex: 1;
}

.cover-upload {
  width: 300px;
}

.image-container {
  width: 100%;
  height: 400px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.empty-cover {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  gap: 8px;
}

.upload-button {
  text-align: center;
}
</style>
